//==================================================================
//  Copyright (C) 2006  Davide Pasca
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//==================================================================
///
///
///
/// Where did I derive this from ? Forgot m(__)m ...
///
//==================================================================

#include <math.h>
#include "fractal.h"

//==================================================================
static const float DELTA = 1e-6f;

//==================================================================
Fractal::Fractal(int nDimensions, unsigned int nSeed, float fH, float fLacunarity) :
	  Noise( nDimensions, nSeed )
{
	_fH = fH;
	_fLacunarity = fLacunarity;
	
	float f = 1;

	for(int i=0; i < MAX_OCTAVES; ++i)
	{
		_fExponent[i] = powf(f, -_fH);
		f *= _fLacunarity;
	}
}

//==================================================================
float Fractal::fBm( float *f, float fOctaves )
{
	// Initialize locals
	int i;
	float fValue = 0;
	float fTemp[MAX_DIMENSIONS];

	for(i=0; i < _dims; i++)
		fTemp[i] = f[i];

	// Inner loop of spectral construction, where the fractal is built
	for(i=0; i < fOctaves; i++)
	{
		fValue += CalcNoise( fTemp ) * _fExponent[i];
		for(int j=0; j< _dims; j++)
			fTemp[j] *= _fLacunarity;
	}

	// Take care of remainder in fOctaves
	fOctaves -= (int)fOctaves;
	if ( fOctaves > DELTA )
		fValue += fOctaves * CalcNoise( fTemp ) * _fExponent[i];

	PCLAMP( fValue, -1, 1 );
	//PASSERT( fValue >= -1 && fValue <= 1 );

	return fValue;
}
